import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { storage } from '@/base/storage';

type UserInfo = {
  /**
   * 用户名
   */
  username: string;
  /**
   * 登录凭证
   */
  accessToken: string;
  /**
   * 用户头像
   */
  [key: string]: any;
};

type State = {
  /**
   * 用户信息
   */
  userInfo: UserInfo;
  vipInfo: any;
  /**
   * 登录状态
   */
  isLogin: boolean;
  vipRemainDays?: number;
};

type Actions = {
  login: (userInfo: Partial<UserInfo>) => void;
  logout: () => void;
  setUserInfo: (userInfo: Partial<UserInfo>) => void;
  setUserVip: (vip: any) => void
  setvipRemainDays: (days: number) => void
};

const initialState: State = {
  userInfo: {
    username: '',
    accessToken: '',
  },
  vipInfo: {},
  isLogin: false,
  vipRemainDays: 0,
};

export const useUserStore = create<State & Actions>()(
  persist(
    immer((set) => ({
      ...initialState,

      /**
       * 登录
       * @param userInfo
       */
      login: (userInfo: Partial<UserInfo>) => {
        if (userInfo?.accessToken) {
          Taro.setStorageSync('accessToken', userInfo?.accessToken);
        }

        set((state: State) => {
          state.userInfo = { ...state.userInfo, ...userInfo };
          state.isLogin = true;
        });
      },

      setvipRemainDays(days) {
        set((state: State) => {
          state.vipRemainDays = days;
        });
      },

      /**
       * 退出登录
       */
      logout: () => {
        Taro.removeStorageSync('accessToken');

        set((state) => {
          state.userInfo = {
            username: '',
            accessToken: '',
          };

          state.isLogin = false;
        });

        Taro.switchTab({ url: '/pages/index/index' });
      },

      setUserVip: (data: any) => {

        set((state) => {
          state.vipInfo = data;
        });
      },

      /**
       * 设置用户信息
       * @param userInfo
       */
      setUserInfo: (userInfo: Partial<UserInfo>) => {
        if (userInfo?.accessToken) {
          Taro.setStorageSync('accessToken', userInfo?.accessToken);
        }

        set((state) => {
          state.userInfo = { ...state.userInfo, ...userInfo };
        });
      },
    })),
    {
      name: 'user-storage',
      partialize: (state) => ({ userInfo: state.userInfo, isLogin: state.isLogin }),
      storage,
    },
  ),
);
